package cn.zxh.csdn_maven.base.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import cn.zxh.csdn_maven.base.pojo.Cookies;
@SuppressWarnings(value={"unused"})
public class GetHtmlFromUrl {
	private static GetHtmlFromUrl getHtmlFromUrl;
	private static URL url;
	private static HttpURLConnection connection;
	private static BufferedReader reader;
	private GetHtmlFromUrl(){
		
	}
	public static GetHtmlFromUrl getInstance() throws UnsupportedEncodingException, IOException{
		if(getHtmlFromUrl==null){
			getHtmlFromUrl = new GetHtmlFromUrl();
		}
		return getHtmlFromUrl;
	}
	public String getHtml(Map<?, ?> params) throws Exception{
		String html="";
		String base_url="";
		if(params==null){
			throw new Exception("参数不能为空");
		}
		if(params.get("base_url")==null){
			throw new Exception("参数base_url不能为空");
		}
		base_url=params.get("base_url").toString();
		url=new URL(base_url);
		connection=(HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestMethod("GET");
		connection.setRequestProperty("Cookie", Cookies.getCookies());
		connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; W…) Gecko/20100101 Firefox/62.0");
		connection.setRequestProperty("Host", params.get("Host")!=null?params.get("Host").toString():"download.csdn.net");
		connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		connection.setRequestProperty("Referer", params.get("Referer")!=null?params.get("Referer").toString():"zxhtom.oschina.io");
		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
		Cookies.setCookies(connection.getHeaderFields().get("Set-Cookie"));
		String tempLine = null;
		while ((tempLine = reader.readLine()) != null) {
			html+=tempLine;
        }
		connection.disconnect();
		return html;
	}
}
